package cn.zcscloud.controller;

import cn.zcscloud.pojo.User;
import cn.zcscloud.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/user")
public class UserController extends HttpServlet {
    UserServiceImpl userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //请求编码
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //获取前端传递的数据
        String action = req.getParameter("action");
        switch (action){
            case "login":
                this.login(req,resp);
                break;
            case "register":
                this.register(req,resp);
                break;
        }
    }

    private void register(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //获取登录数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        User user = userService.findUserByName(username);
        if (user == null){  //用户名不能存在
            userService.register(new User(username,password));
            resp.getWriter().write("<h3>注册成功</h3>");
        }else {
            resp.getWriter().write("<h3>用户名重复，请换个用户名重试</h3>");
        }


    }

    private void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //获取登录数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        User user = userService.login(username, password);

        if (user != null){
            resp.getWriter().write("<h3>登录成功</h3>");
        }else {
            resp.getWriter().write("<h3>登录失败</h3>");
        }


    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
